<template>
	<view>
		<uni-search-bar :placeholder="$lang('查询')" readonly cancelButton="none" @click="focus" >
		</uni-search-bar>
		<uni-popup ref="popup" background-color="#fff" :is-mask-click="true">
			<view class="overflow-y-auto p-10">
				<uni-search-bar :placeholder="$lang('查询')" @confirm="search" :focus="true" v-model="searchValue" @cancel="cancel"
					@input="search">
				</uni-search-bar>
				<view v-for="option in options" class="m-5">
					<view class=" border-b-[1px] border-solid pb-40 " @click="menuTab(option.item.path)">
							<view class="float-left">
								<view class="text-[#437fff]">	
									{{ option.item.title.join(' > ') }}
									<view class="text-6 text-[#999]">{{ option.item.path }}</view>
								</view>
							</view>
							<view :class="`float-right iconfont icon-star text-2xl ${option.item.isHover?'text-[#ff0000]':'text-[#999]'}`"  @click.stop="handleLove(option.item)"></view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import usePermissionStore from '@/store/modules/permission'
	import {
		isHttp
	} from '@/utils/validate'
	import {
		getNormalPath, findItem, color16 
	} from '@/utils/common.js'
	import Fuse from 'fuse.js'
	import storage from '@/utils/storage.js'
	import useUserStore from '@/store/modules/user'
	const { proxy } = getCurrentInstance()
	const searchValue = ref("")
	const popup = ref("popup")
	const routes = computed(() => usePermissionStore().routes)
	const commonRouters = computed(() => usePermissionStore().commonlyUsedRoutes)
	const searchPool = ref([])
	const options = ref([])
	const fuse = ref(undefined)
	onMounted(async() => {
		setTimeout(()=>{
			searchPool.value = generateRoutes(routes.value)
		},3000)
	})
	watchEffect(async() => {
		setTimeout(()=>{
			searchPool.value = generateRoutes(routes.value)
		},3000)
	})
	watch(searchPool, (list) => {
		initFuse(list)
	})
	watch(commonRouters, async() => {
		setTimeout(()=>{
			searchPool.value = generateRoutes(routes.value)
		},3000)
	},{
		deep:true
	})
	function menuTab(e) {
		cancel()
		proxy.$tab.navigateTo(e.indexOf('/') == 0 ? e : `/${e}`);
	}
	function focus(){
		searchValue.value=""
		options.value = []
		popup.value.open('center')
	}
	function cancel(){
		popup.value.close()
	}
	function search(query) {
		if (query !== '') {
			options.value = fuse.value.search(query)
		} else {
			options.value = []
		}
	}

	function initFuse(list) {
		fuse.value = new Fuse(list, {
			shouldSort: true,
			threshold: 0.4,
			location: 0,
			distance: 100,
			minMatchCharLength: 1,
			keys: [{
					name: 'title',
					weight: 0.7
				},
				{
					name: 'path',
					weight: 0.3
				}
			]
		})
	}

	function generateRoutes(routes, basePath = '', prefixTitle = [], query = {}) {
		let res = []

		for (const r of routes) {
			// skip hidden router
			if (r.hidden && r.name != "pda") {
				continue
			}
			const p = r.path.length > 0 && r.path[0] === '/' ? r.path : '/' + r.path
			const data = {
				path: r.component,
				title: [...prefixTitle],
				icon: 'menu',
				menuTitle: '',
				titleKey: ''
			}
			
			var arraryObjectLocal = storage.getJSON(`${useUserStore().userName}_commonlyUseMenu`) || []
			let index = findItem(arraryObjectLocal, 'path', data.path)
			let isHover=index <= -1?false:true
				data.isHover=isHover
			if (r.meta && r.meta.title) {
				data.title = [...data.title, r.meta.title]
				data.icon = r.meta.icon
				data.menuTitle = r.meta.title
				data.titleKey =  r.meta.title
				if (r.redirect !== 'noRedirect') {
					// only push the routes with title
					// special case: need to exclude parent router without redirect
					res.push(data)
				}
			}
			if (r.query) {
				data.query = r.query
			}

			// recursive child routes
			if (r.children) {
				const tempRoutes = generateRoutes(r.children, data.path, data.title)
				if (tempRoutes.length >= 1) {
					res = [...res, ...tempRoutes]
				}
			}
		}
		return res
	}
	
	/**
	 * 添加快捷菜单
	 * @param {*} item
	 */
	function handleLove(item) {
	  var arraryObjectLocal = storage.getJSON(`${useUserStore().userName}_commonlyUseMenu`) || []
	  var len = 12
	  if (arraryObjectLocal.length >= len) {
	    proxy.$modal.msgError(`最多可添加${len}个常用菜单`)
	    return
	  }
	  let index = findItem(arraryObjectLocal, 'path', item.path)
	  if (index <= -1) {
		item.isHover=true
	    arraryObjectLocal.push({ ...item, color: color16() })
	    storage.setJSON(`${useUserStore().userName}_commonlyUseMenu`, arraryObjectLocal)
	    proxy.$modal.msgSuccess('添加成功')
	    usePermissionStore().setCommonlyUsedRoutes()
	  } else {
	    proxy.$modal.msgError('该菜单已存在')
	  }
	}
</script>

<style lang="scss">
	::v-deep .uni-popup .uni-popup__wrapper {
		@apply flex justify-center rounded-t-10 h-[100%] w-[100%] mt-50;
	}
</style>